package com.lizardmind.haofudoctor.test

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.linxiao.framework.util.ke
import com.linxiao.framework.widget.Section.SectionRecyclerHeadersAdapter
import com.lizardmind.haofudoctor.R
import com.lizardmind.haofudoctor.other.TypeDocumentsBean
import kotlinx.android.synthetic.main.test_item_problem.view.*
import kotlinx.android.synthetic.main.test_item_problem_header.view.*
import org.jetbrains.anko.collections.forEachWithIndex
import org.jetbrains.anko.sdk25.coroutines.onCheckedChange
import org.jetbrains.anko.sdk25.coroutines.onClick

/**
 *
 * Created by Extends on 2017/11/6 11:04
 */
class DiagnoseTestAdapter(con:Context,data:TypeDocumentsBean,answer:IntArray?,span:Int): RecyclerView.Adapter<DiagnoseTestAdapter.ViewHoder>(),
        SectionRecyclerHeadersAdapter<DiagnoseTestAdapter.HeadViewHodler> {
    val context:Context = con
    private var isAnswer=false
    var lock = false
    private val list= arrayListOf<Array<String>?>()//Array<String>{一级id，一级名称，二级名称，二级是否点击（0->false,1->true）,是否单选（1->单选，2->多选）}
    init {
        isAnswer=answer!=null
        data.data.forEachWithIndex { i, pd ->
            pd.options.forEachIndexed { index, it ->
                val temp = if(answer!=null){
                    (answer[i] shr (pd.options.size-1-index) and 1).toString()
                }else "0"

                list.add(arrayOf(i.toString(),pd.problem_title,it,temp,pd.type.toString()))
            }
            while (list.count()%span!=0){
                list.add(null)
            }
        }
    }

    override fun getItemCount(): Int=list.count()

    override fun onBindViewHolder(holder: ViewHoder, position: Int) {
        if(list[position]!=null){
            holder.itemView.tip_ctv.apply {
                visibility = View.VISIBLE
                text = list[position]!![2]
                lock=true
                isChecked = list[position]!![3]!="0"

                if(list[position]!![4]=="1"){
                    setButtonDrawable(R.drawable.abc_btn_radio_material)
                }else{
                    setButtonDrawable(R.drawable.abc_btn_check_material)
                }

                onClick {
                    if(list[position]!![4]=="1"){
                            listRadioChange(position,list[position]!![0],isChecked)
                    }else{
                        listMultiChange(position,isChecked)
                    }
                }
            }
        }else{
            holder.itemView.tip_ctv.visibility = View.GONE
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHoder {
        return ViewHoder(LayoutInflater.from(parent.context).inflate(R.layout.test_item_problem,parent,false))
    }

    override fun getHeaderId(position: Int): Long {
        return (position downTo 0)
                .firstOrNull { list[it]!=null }
                ?.let { list[it]!![0].toLong() }
                ?: -1
    }

    override fun onCreateHeaderViewHolder(parent: ViewGroup): HeadViewHodler {
        return HeadViewHodler(LayoutInflater.from(parent.context).inflate(R.layout.test_item_problem_header,parent,false))
    }

    override fun onBindHeaderViewHolder(holder: HeadViewHodler, position: Int) {
        holder.itemView.tiph_text.text=list[position]!![1]
    }

    override fun isNull(position: Int): Boolean = list[position]==null

    /**
     * 标准项view
     */
    class ViewHoder(view:View) : RecyclerView.ViewHolder(view)

    /**
     * 头部view
     */
    class HeadViewHodler(view:View) : RecyclerView.ViewHolder(view)


    /**
     * 当前组是单选时
     */
    private fun listRadioChange(position: Int,headerId:String,isCheck:Boolean){
        if(isCheck) {
            list.filterNotNull().filter { it[0] == headerId }.forEach { it[3] = "0" }
            list[position]!![3] = "1"
        }else{
            list[position]!![3] = "0"
        }
        notifyDataSetChanged()
    }

    /**
     * 当前组是多选时
     */
    private fun listMultiChange(position: Int,isCheck:Boolean){
        if(isCheck) {
            list[position]!![3] = "1"
        }else{
            list[position]!![3] = "0"
        }
        notifyDataSetChanged()
    }

    fun getAnswer():String{
        var temp =-1L
        val a = arrayListOf<String>()
        var t = ""
        for (s in list) {
            if(s!=null){
                if(s[0]!=t){
                    if(t!=""){
                        a.add(temp.toString())
                    }
                    temp =0L
                    t=s[0]
                }
                temp = (temp shl 1)+s[3].toInt()
            }
        }
        a.add(temp.toString())
        return a.joinToString(",","[","]")
    }

}